﻿using System;
using System.Linq;
using System.Threading;
using Common.Logging;
using In.Api.Dto.Notify.Notification;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;

namespace Out.TaskRunner.RmqWorkers
{
    public class HospMessageWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(HospMessageWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new HospMessageConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.NotificationType == "CommonNotice")
                    {
                        return ProcessCommonNotice(msg.NotificationInfo, channel);
                    }
                    //else if (msg.NotificationType == "HaltNotice")
                    //{
                    //    return ProcessHaltNotice(msg.NotificationInfo, channel);
                    //}
                    //else if (msg.NotificationType == "RefundNotice")
                    //{
                    //    return ProcessRefundNotice(msg.NotificationInfo, channel);
                    //}

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessCommonNotice(string notificationInfo, WrapperChannel channel)
        {
            var commonNotice = JsonConvert.DeserializeObject<CommonNotice>(notificationInfo);
            using (var ctx = new FsssdqfybjyEntities())
            {
                switch (commonNotice.NoticeType)
                {
                    // 缴费通知
                    case 0:
                        {
                            #region 插入新调查问卷

                            var paperQuery =
                            ctx.SIWaitInvestigatePapers.FirstOrDefault(x => x.ClinicNo == commonNotice.ClinicNo);
                            if (paperQuery == null)
                            {
                                var paper = new SIWaitInvestigatePaper();
                                paper.Name = commonNotice.Name;
                                paper.CardNo = commonNotice.CardNo;
                                paper.CardType = 0;
                                paper.PatientId = commonNotice.PatientId;
                                paper.ClinicNo = commonNotice.ClinicNo;
                                paper.Type = 0;
                                paper.CreateTime = DateTime.Now;
                                paper.Status = 0;
                                paper.SubmitCount = 0;
                                var now = DateTime.Now;
                                if (now.Hour >= 6 && now.Hour < 18)
                                {
                                    //白天的诊疗
                                    paper.NeedSendTime = now.Date.AddHours(18).AddMinutes(now.Minute);
                                }
                                else
                                {
                                    //晚上的诊疗
                                    if (now.Hour > 6)
                                    {
                                        paper.NeedSendTime = now.Date.AddDays(1).AddHours(10).AddMinutes(now.Minute);
                                    }
                                    else
                                    {
                                        paper.NeedSendTime = now.Date.AddHours(10).AddMinutes(now.Minute);
                                    }
                                }
                                paper.IsSended = 0;
                                ctx.SIWaitInvestigatePapers.Add(paper);
                                ctx.SaveChanges();
                            }

                            #endregion

                            var hospCards = ctx.HospCards.Where(x => x.CardNo == commonNotice.CardNo && x.RecStatus == 1).Select(x => new { CardId = x.Id }).ToList();
                            foreach (var hospCard in hospCards)
                            {
                                //MessageHelper.SendNewPaperMsg(hospCard.CardId.ToInt32OrDefault());
                                MessageHelper.SendNewBillMsg(hospCard.CardId.ToInt32OrDefault());
                            }
                        }
                        break;
                    // 检验单通知
                    case 1:
                        {
                            var hospCards = ctx.HospCards.Where(x => x.CardNo == commonNotice.CardNo && x.RecStatus == 1).ToList();
                            foreach (var hospCard in hospCards)
                            {
                                MessageHelper.SendNewInspectionMsg(hospCard.Id.ToInt32OrDefault());
                            }
                        }
                        break;
                    // 检查单通知
                    case 2:
                        {
                            var hospCards = ctx.HospCards.Where(x => x.CardNo == commonNotice.CardNo && x.RecStatus == 1).ToList();
                            foreach (var hospCard in hospCards)
                            {
                                MessageHelper.SendNewCheckMsg(hospCard.Id.ToInt32OrDefault());
                            }
                        }
                        break;
                    case 3: //候诊队列的通知
                        {
                            var waitNo = commonNotice.AppNo;
                            var deptName = commonNotice.DeptName;
                            var doctorName = commonNotice.DoctorName;
                            var hospCards = ctx.HospCards.Where(x => x.CardNo == commonNotice.CardNo && x.RecStatus == 1).ToList();
                            foreach (var hospCard in hospCards)
                            {
                                MessageHelper.SendQueueMsg(hospCard.Id.ToInt32OrDefault(), waitNo, deptName, doctorName);
                            }
                        }
                        break;
                    case 7: //过号提醒
                        {
                            var hospCards = ctx.HospCards.Where(x => x.CardNo == commonNotice.CardNo && x.RecStatus == 1).ToList();
                            foreach (var hospCard in hospCards)
                            {
                                MessageHelper.SendOverQueueMsg(hospCard.Id.ToInt32OrDefault());
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            return new ConsumedResult
            {
                Ack = true
            };
        }

        private ConsumedResult ProcessHaltNotice(string notificationInfo, WrapperChannel channel)
        {
            var haltInfo = JsonConvert.DeserializeObject<HaltInfo>(notificationInfo);

            var haltDate = DateTime.Now;
            if (!DateTime.TryParse(haltInfo.HaltDate, out haltDate))
            {
                return new ConsumedResult
                {
                    Ack = true
                };
            }

            if (haltDate < DateTime.Now.Date)
            {
                return new ConsumedResult
                {
                    Ack = true
                };
            }

            //using (var ctx = new FsssdqfybjyEntities())
            //{
            //    var appoints =
            //        ctx.ApptOrders.IsStatus(ApptOrderExtensions.OrderStatus.取号成功)
            //        .Where(
            //            x =>
            //                x.DeptId == haltInfo.DeptId && x.DoctorId == haltInfo.DoctorId &&
            //                x.RegType == haltInfo.RegType && x.TimeSlice == haltInfo.TimeSlice &&
            //                x.RegDate == haltInfo.HaltDate).Select(x => new { x.Id });

            //    foreach (var apptOrder in appoints)
            //    {
            //        MessageHelper.SendHaltMsg(apptOrder.Id);
            //    }
            //}

            return new ConsumedResult
            {
                Ack = true
            };
        }

        private ConsumedResult ProcessRefundNotice(string notificationInfo, WrapperChannel channel)
        {
            var refundInfo = JsonConvert.DeserializeObject<RefundInfo>(notificationInfo);

            switch (refundInfo.RefundType)
            {
                case 0:
                    //退挂号费通知
                    using (var ctx = new FsssdqfybjyEntities())
                    {
                        var appointOrder = ctx.ApptOrders.FirstOrDefault(x => x.OrderNo == refundInfo.OrderId);
                        if (appointOrder != null)
                        {
                            if (appointOrder.PayState != ApptOrderExtensions.PayState.已退款.ToInt32().ToString())
                            {
                                //收到退款通知，原订单状态不为已退款的，均认为是窗口退款28
                                appointOrder.PayState = ApptOrderExtensions.PayState.已退款.ToInt32().ToString();
                                //appointOrder.OrderStatus = ApptOrderExtensions.OrderStatus.窗口退号成功.ToInt32();
                                appointOrder.RefundReason = appointOrder.RefundReason + "|退款通知确认退款";
                                appointOrder.RefundTime = refundInfo.RefundTime;
                                ctx.SaveChanges();
                            }
                        }
                    }
                    break;
                case 1:
                    //退处方费（(包括药费，检查/检验费)通知
                    using (var ctx = new FsssdqfybjyEntities())
                    {
                        //var billOrder = ctx.ClinRecipeOrders.FirstOrDefault(x => x.ClinicNo == refundInfo.ClinicNo);
                        //if (billOrder != null)
                        //{
                        //    //在微信上缴费
                        //    if (billOrder.PayState != BillOrderExtensions.PayState.已退款.ToInt32().ToString())
                        //    {
                        //        //收到退款通知，原订单状态不为已退款的，均认为是10窗口退款成功
                        //        billOrder.PayState = BillOrderExtensions.PayState.已退款.ToInt32().ToString();
                        //        billOrder.OrderStatus = BillOrderExtensions.OrderStatus.窗口退款成功.ToInt32();
                        //        billOrder.RefundTime = refundInfo.RefundTime;
                        //        billOrder.Remark = billOrder.Remark + "|退款通知：确认退款";
                        //        ctx.SaveChanges();
                        //    }
                        //}
                    }
                    break;
            }

            return new ConsumedResult
            {
                Ack = true
            };
        }
    }
}